package com.example.java_chatroom.component;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.concurrent.ConcurrentHashMap;

@Component
public class OnlineUserManager {
    //要考虑线程安全问题
    private ConcurrentHashMap<Integer, WebSocketSession> sessions = new ConcurrentHashMap<>();
    //1）用户上线给哈希表中插入键值对
    public void online(int userId,WebSocketSession session){
        if(sessions.get(userId) != null){
            //此时用户已经在线，登录失败
            System.out.println("["+ userId +"] 已经登录，登录失败！");
            return;
        }
        sessions.put(userId,session);
        System.out.println("[" + userId +"] 上线！");
    }
    //2）用户下线，哈希表删除元素
    public void offline(int userId,WebSocketSession session){
        WebSocketSession existSession = sessions.get(userId);
        if (existSession == session){
            //如果这两session是同一个，才真正进行下线操作
            sessions.remove((userId));
            System.out.println("[" + userId +"] 下线！");
        }
    }
    //3）
    public WebSocketSession getSession(int userId) {
        return sessions.get(userId);
    }
}
